import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:merchants/providers/providers.dart';

class RoleEditScreen extends ConsumerStatefulWidget {
  final Map<String,dynamic> role;
  const RoleEditScreen({super.key, required this.role});

  @override
  ConsumerState<RoleEditScreen> createState() => _RoleEditScreenState();
}

class _RoleEditScreenState extends ConsumerState<RoleEditScreen> {
  late Future<List<Map<String,dynamic>>> _futurePerms;
  late Set<int> _selectedIds;

  @override
  void initState() {
    super.initState();
    _selectedIds = <int>{};
    _futurePerms = ref.read(permissionServiceProvider).fetchPermissions();
    final ids = (widget.role['permissionIds'] as List?)?.cast<int>() ?? [];
    _selectedIds = ids.toSet();
  }

  void _loadRolePerms() async {
    // backend role fetch included permissionIds? not yet -> skip
  }

  void _toggle(int id) {
    setState(() {
      if (_selectedIds.contains(id)) {
        _selectedIds.remove(id);
      } else {
        _selectedIds.add(id);
      }
    });
  }

  Future<void> _save() async {
    await ref.read(roleServiceProvider).updateRole(widget.role['id'] as int, permissionIds: _selectedIds.toList());
    if (mounted) Navigator.pop(context, true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('编辑角色: ${widget.role['name']}')),
      body: FutureBuilder<List<Map<String,dynamic>>>(
        future: _futurePerms,
        builder: (ctx,snap){
          if(snap.connectionState==ConnectionState.waiting){return const Center(child:CircularProgressIndicator());}
          if(snap.hasError){return Center(child: Text('加载失败:${snap.error}'));}
          final perms=snap.data??[];
          return ListView(
            children: perms.map((p){
              final id=p['id'] as int;
              return CheckboxListTile(
                title: Text('${p['name']} (${p['code']})'),
                value: _selectedIds.contains(id),
                onChanged: (_) => _toggle(id),
              );
            }).toList(),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _save,
        child: const Icon(Icons.save),
      ),
    );
  }
} 